/**
 * 
 */
package de.fsujena.chat_pi.server;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * The network listener is used to listen for new clients at a given port. It launches
 * a new message listener, which will be responsible for the direct communication with 
 * the client.
 * 
 * @author Erik Hebestreit
 * @see MessageListener
 */
public class NetworkListener extends Thread {
	Server serverObject;
	ServerSocket server;
	List<MessageListener> messageListener = new ArrayList<MessageListener>();
	
	/**
	 * constructor for new network listener to listen at a specific port
	 * 
	 * @param port specifies the port number where the network listener listens
	 */
	public NetworkListener(int port, Server serverObject) throws IOException {
		this.serverObject = serverObject;
		server = new ServerSocket(port);
	}
	
	/**
	 * launch network listener thread
	 */
	public void run() {
		while (true) {
			try {
				// wait for a new client to connect to the server and start a new message
				// listener			
				messageListener.add(new MessageListener(server.accept(),serverObject));
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			
			// get the index of the element just added (last one) and launch the thread
			messageListener.get(messageListener.size() - 1).start();
		}
	}
	/**
	 * removes connection to client 
	 * @param user username of the client to be removed
	 */
	public void removeClient(String user){
		// TODO can be simplified
		
		for(int i=0;i<messageListener.size();i++){
			if(messageListener.get(i).username.equals(user))messageListener.remove(i);
		}
		return;
	}
}
